package cn.gift.service.impl;

import cn.gift.client.AuthClient;
import cn.gift.constants.State;
import cn.gift.domain.Employee;
import cn.gift.domain.LoginUser;
import cn.gift.domain.Tenant;
import cn.gift.dto.TenantEnteringDto;
import cn.gift.exception.BusinessAssert;
import cn.gift.exception.BusinessException;
import cn.gift.exception.ErrorCode;
import cn.gift.mapper.EmployeeMapper;
import cn.gift.mapper.TenantMapper;
import cn.gift.query.TenantQuery;
import cn.gift.service.ITenantService;
import cn.gift.util.AjaxResult;
import cn.gift.util.PageList;
import cn.gift.vo.result.TenantVo;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ZhaoLc
 * @since 2023-04-24
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {

    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private AuthClient authClient;


    @Override
    public PageList selectPageList(TenantQuery query) {
        Page<TenantVo> page = new Page<TenantVo>(query.getPage(),query.getRows());
        List<TenantVo> tenantVos = tenantMapper.loadPageList(page,query);
        return new PageList<>(page.getTotal(),tenantVos);
    }

    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public void settlement(TenantEnteringDto tenantEnteringDto) {
        // 1.参数校验
        if(verifyParams(tenantEnteringDto)){
            throw new BusinessException("存在信息未填写,请检查!");
        }
        // 1.1 验证密码校验
        BusinessAssert.isEq(tenantEnteringDto.getConfirmPwd(),tenantEnteringDto.getEmployee().getPassword(),ErrorCode.CODE_4002);
        // 1.2 店铺名称重复校验
        Wrapper<Tenant> tenantWrapper = new EntityWrapper<>();
        tenantWrapper.eq("company_name",tenantEnteringDto.getTenant().getCompanyName());
        BusinessAssert.isExist(tenantMapper.selectCount(tenantWrapper), ErrorCode.CODE_4001);
        // 1.3 管理员重复校验
        Employee employee = new Employee();
        employee.setUsername(tenantEnteringDto.getEmployee().getUsername());
        Employee employeeResult = employeeMapper.selectOne(employee);

        LoginUser loginUserSearch = new LoginUser();
        loginUserSearch.setUsername(tenantEnteringDto.getEmployee().getUsername());
        LoginUser loginUserResult = (LoginUser) authClient.getLoginUser(loginUserSearch).getResultObj();
        BusinessAssert.isExist(loginUserResult, ErrorCode.CODE_4004);

        // 2. 百度审核
        // TODO
        // 3. 调用权限服务添加login-info信息
        LoginUser loginUser = new LoginUser();
        BeanUtils.copyProperties(tenantEnteringDto.getEmployee(),loginUser);
        AjaxResult ajaxResult = authClient.addOrUpdate(loginUser);

        // 5. 保存租户
        Tenant tenant = new Tenant();
        BeanUtils.copyProperties(tenantEnteringDto.getTenant(),tenant);
        tenant.setRegisterTime(new Date());
        tenant.setState(State.TENANT_STATE_WAIT_AUDIT);
        tenant.setAdminId(Long.parseLong(ajaxResult.getResultObj().toString()));
        tenantMapper.insert(tenant);
        // 6. 租户和套餐中间表
        tenantMapper.saveTenantMeal(tenant.getId(),tenantEnteringDto.getMealId());
        // 7. 添加审核日志
        // 8. 发邮件激活操作

        // TODO
        //employeeMapper.insert(employeeResult);
    }

    private boolean verifyParams(TenantEnteringDto tenantEnteringDto) {
        Tenant tenant = tenantEnteringDto.getTenant();
        if(StringUtils.isEmpty(tenant.getCompanyName()) || StringUtils.isEmpty(tenant.getCompanyNum())
                ||StringUtils.isEmpty(tenant.getTypeId()) || StringUtils.isEmpty(tenant.getAddress())
                ||StringUtils.isEmpty(tenant.getAdminId())){
            return false;
        }
        Employee employee = tenantEnteringDto.getEmployee();
        if(StringUtils.isEmpty(employee.getUsername()) || StringUtils.isEmpty(employee.getPassword())
                ||StringUtils.isEmpty(employee.getEmail()) || StringUtils.isEmpty(tenantEnteringDto.getConfirmPwd())) {
            return false;
        }
        return !StringUtils.isEmpty(tenantEnteringDto.getMealId());
    }
}
